package cn.ffcs.businessrequest.service;


import java.io.File;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;

import cn.ffcs.bpm.model.ProcessConfigDetail;
import cn.ffcs.businessrequest.dao.DocContentDAO;
import cn.ffcs.businessrequest.dao.ReqDocuDAO;
import cn.ffcs.businessrequest.model.BusinessRequest;
import cn.ffcs.businessrequest.model.DocContent;
import cn.ffcs.businessrequest.model.ReqDocu;
import cn.ffcs.base.service.BaseService;
import cn.ffcs.system.dict.model.Dict;

/**
 * 业务需求交互单服务层<br/>
 * <table>
 * <tr>
 * <td>负责人/principal:</td>
 * <td colspan="2">pany</td>
 * <tr>
 * <td>修改记录/revision:</td>
 * <td colspan="2"></td>
 * </tr>
 * <tr>
 * <td>日期:</td>
 * <td>修改人:</td>
 * <td>修改说明:</td>
 * </tr>
 * <tr>
 * <td></td>
 * <td></td>
 * <td></td>
 * </tr>
 * </table>
 * @author pany
 * @version $Id$
 */
public class ReqDocuService<D extends ReqDocu> extends BaseService<D> implements IReqDocuService<D>
{
    private static final int BUFFER_SIZE = 512 * 1024;

    /** 文档DAO **/
    private ReqDocuDAO reqDocuDAO;
    /** 文档内容DAO **/
    private DocContentDAO docContentDAO;
    
    /**
     * ///将旧的需求单的附件复制到新的需求单上，需要两个需求单的id
     * TODO 请输入方法说明
     * @param refEntity 源需求单实体类
     * @param sourEntityId  源需求单实体id
     * @param objEntityId   目标需求单实体id
     * @return
     */
    public String copyReqDocu(String refEntity,String sourEntityId,BusinessRequest objEntityId){
        Criterion cond1 = Restrictions.eq("refEntity", refEntity);
        Criterion cond2 = Restrictions.eq("refEntityId", sourEntityId);
        Criterion condDocu = Restrictions.and(cond1, cond2);
        List<ReqDocu> reqDocus = (List<ReqDocu>)this.findBy(condDocu);
        D newDocu=null;
        for(ReqDocu tmp:reqDocus){
            newDocu=(D)new ReqDocu();
            newDocu.setBegin(tmp.getBegin());
            newDocu.setContent(tmp.getContent());
            newDocu.setCreator(tmp.getCreator());
            newDocu.setDocType(tmp.getDocType());
            newDocu.setEnd(tmp.getEnd());
            newDocu.setFullName(tmp.getFullName());
            newDocu.setLength(tmp.getLength());
            newDocu.setName(tmp.getName());
            newDocu.setPrefix(tmp.getPrefix());
            newDocu.setProcessDetail(tmp.getProcessDetail());
            newDocu.setVersion(tmp.getVersion());
            newDocu.setRefEntity(objEntityId.getClass().getName());
            newDocu.setRefEntityId(objEntityId.getId()+"");
            this.saveOrUpdate(newDocu);
        }
        
        return null;
    }
    
    public String saveReqDocu(String businessRequestId,String processDetailId,List<String> docTypeIds,List<File> uploads,
            List<String> fileNames, String[] reqDocuIDs,String[] delIDs,List<File> otherFiles){

        // 保存附件
        if (otherFiles != null)
        {
            int i = 0;
            for (i = 0; i < otherFiles.size(); i++)
            {
                try
                {
                    File file = otherFiles.get(i);
                    byte[] result = new byte[BUFFER_SIZE];
                    result = FileUtils.readFileToByteArray(file);
                    FileUtils.forceDelete(file);
                    
                    String fileName = file.getName();
                    String fullName = fileName;
                    String name = fullName.substring(0, fullName.lastIndexOf("."));
                    String prefix = fullName.substring(
                            fullName.lastIndexOf(".") + 1, fullName.length());

                    ReqDocu reqDocu = new ReqDocu();
                    reqDocu.setRefEntity(new BusinessRequest().getClass().getName());
                    reqDocu.setRefEntityId(businessRequestId);
                    reqDocu.setProcessDetail(new ProcessConfigDetail(new Integer(processDetailId)));
                    reqDocu.setDocType(null);
                    reqDocu=getReqDocuId(reqDocu);

                    DocContent doc=new DocContent();
                    doc.setContent(result);
                    docContentDAO.save(doc);
                    reqDocu.setContent(doc);
                    reqDocu.setFullName(fullName);
                    reqDocu.setName(name);
                    reqDocu.setPrefix(prefix);
                    // 设置基本信息
                    setBaseInfo(reqDocu);
                    reqDocuDAO.save(reqDocu);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
        return this.saveReqDocu( businessRequestId,processDetailId,docTypeIds,uploads,
                fileNames,reqDocuIDs, delIDs);
    }
    
    /**
     * 保存产品资料操作
     */
    @SuppressWarnings("unchecked")
    public String saveReqDocu(String businessRequestId,String processDetailId,List<String> docTypeIds,List<File> uploads,
            List<String> fileNames, String[] reqDocuIDs,String[] delIDs)
    {
        String ids="";
        // 删除附件
        if (delIDs != null && delIDs.length > 0)
        {
            for (String id : delIDs)
            {
                reqDocuDAO.deleteById(id);
            }
        }
        // 保存附件
        if (uploads != null)
        {
            int i = 0;
            for (i = 0; i < uploads.size(); i++)
            {
                try
                {
                    File file = uploads.get(i);
                    byte[] result = new byte[BUFFER_SIZE];
                    result = FileUtils.readFileToByteArray(file);
                    FileUtils.forceDelete(file);

                    String fileName = fileNames.get(i);
                    String fullName = fileName;
                    String name = fullName.substring(0, fullName.lastIndexOf("."));
                    String prefix = fullName.substring(
                            fullName.lastIndexOf(".") + 1, fullName.length());

                    ReqDocu reqDocu = new ReqDocu();
                    reqDocu.setRefEntity(new BusinessRequest().getClass().getName());
                    reqDocu.setRefEntityId(businessRequestId);
                    reqDocu.setProcessDetail(new ProcessConfigDetail(new Integer(processDetailId)));
                    reqDocu.setDocType(new Dict(new Integer(docTypeIds.get(i))));
                    reqDocu=getReqDocuId(reqDocu);

                    DocContent doc=new DocContent();
                    doc.setContent(result);
                    docContentDAO.save(doc);
                    reqDocu.setContent(doc);
                    reqDocu.setFullName(fullName);
                    reqDocu.setName(name);
                    reqDocu.setPrefix(prefix);
                    // 设置基本信息
                    setBaseInfo(reqDocu);
                    if (reqDocu.getId() == null || reqDocu.getId() == 0){
                        reqDocuDAO.save(reqDocu);
                        ids=ids+","+reqDocu.getId();
                    }else{
                        reqDocuDAO.update(reqDocu);
                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
        return ids;
    }
    
    public ReqDocu getReqDocuId(ReqDocu reqDocu){
        Criterion cond1 = Restrictions.eq("refEntity", new BusinessRequest().getClass().getName());
        Criterion cond2 = Restrictions.eq("refEntityId", reqDocu.getRefEntityId());
        Criterion cond3 = Restrictions.eq("processDetail", reqDocu.getProcessDetail());
        Criterion cond4 = Restrictions.eq("docType", reqDocu.getDocType());
        Criterion cond5 = Restrictions.and(cond1, cond2);
        Criterion cond6 = Restrictions.and(cond4, cond3);
        Criterion condDocu = Restrictions.and(cond5, cond6);
        List<ReqDocu> reqDocus = (List<ReqDocu>)this.findBy(condDocu);
        if(reqDocus!=null&&reqDocus.size()>0){
            return reqDocus.get(0);
        }
        return reqDocu;
    }
    
    public DocContentDAO getDocContentDAO()
    {
        return docContentDAO;
    }
    public void setDocContentDAO(DocContentDAO docContentDAO)
    {
        this.docContentDAO = docContentDAO;
    }
    public ReqDocuDAO getReqDocuDAO()
    {
        return reqDocuDAO;
    }
    public void setReqDocuDAO(ReqDocuDAO reqDocuDAO)
    {
        this.reqDocuDAO = reqDocuDAO;
    }

}

